import express from 'express'
import { net } from 'electron'
import getCache from '../helper/cache.js'
import cors from 'cors'
const app = express()

// 启用 CORS 支持
app.use(cors())
export default function useExpress(port = 36998) {
  app.get('/coverjs', async (req, res) => {
    const request = net.request({
      url: req.query.url + '?k=localhost:' + port
    })
    request.on('response', (response) => {
      let data = ''

      // 监听数据事件
      response.on('data', (chunk) => {
        data += chunk
      })

      // 监听结束事件
      response.on('end', () => {
        const cache = getCache()
        const item = cache.find((d) => req.query.url.indexOf(d.keyword) > -1)
        const s = data.replace(item.origin, item.rewrite)
        res.send(s)
      })
    })
    // 发送请求
    request.end()

    // axios
    //   .get(req.query.url + '?k=localhost:36998', {
    //     maxContentLength: Infinity, // 设置响应内容的最大长度为无限制
    //     maxBodyLength: Infinity // 设置请求体的最大长度为无限制
    //   })
    //   .then((response) => {
    //     const cache = getCache()
    //     const item = cache.find((d) => req.query.url.indexOf(d.keyword) > -1)
    //     const s = response.data.replace(item.origin, item.rewrite)
    //     res.send(s)
    //   })
    //   .catch((err) => {
    //     res.status(500).send('Internal Server Error')
    //   })
  })

  app.listen(port, () => {
    console.log(`Server is running at http://localhost:${port}`)
  })
}
